import {ref, reactive, getCurrentInstance} from 'vue'
import type {Order} from '@/TS/Hooks/Home/components/Order'
import * as $http from '@/utlis/interface/orderDlatils'
import {changeTitleText} from '@/utlis/setStatusText'
import {GetDistance} from "@/utlis/uni_api";
import {riderLocationCache} from "@/Pinia";
import { NavBar } from 'vant';

interface loactionData {
    lng: number,
    lat: number
}

interface AddConfig {
    Type: number | null
    Addicon: boolean
    AddKm: boolean
    Adddesc: boolean
}

interface routeLine {
    points: Array<{ latitude: string, longitude: string }>,
}

interface covers {
    startingLatitude: number | string | null,
    startingLongitude: number | string | null,
    terminalLatitude: number | string | null,
    terminalLongitude: number | string | null,
}

export default (proxy: any) => {
    // 位置组件配置
    const AddConfig = reactive<AddConfig>({
        Type: null,
        Addicon: true,
        AddKm: true,
        Adddesc: true,
    })
    // tabs分类默认值
    const Type = ref<number>()
    const confirmChange = () => {
    }
    //打电话联系商家
    const callPhone = (phone: string) => {
        console.log("phone = " + phone)
        if (phone) {
            uni.makePhoneCall({
                phoneNumber: phone,
            })
        }
    }

    let timeData = reactive<Order.timeData>({})
    const onChange = (e: any) => {
        timeData.hours = e.hours >= 10 ? e.hours : '0' + e.hours
        timeData.minutes = e.minutes >= 10 ? e.minutes : '0' + e.minutes
        timeData.seconds = e.seconds >= 10 ? e.seconds : '0' + e.seconds
    }

    //获取当前订单详情
    /*   AddConfigType   订单状态区分
           0为新任务
           1为待配送
           2位待收货
    */
    let orderObj = reactive<any>({
        id: null,
        deliveryTime: null,
        expireTime: null,
        predictTime: null,
        goodsName: null,
        goodsNum: null,
        locationVO: null,
        mobile: null,
        name: null,
        orderNo: null,
        orderType: null,
        pickAddress: null,
        pickGoodsTime: null,
        pickName: null,
        pickPhone: null,
        placeOrderTime: null,
        price: null,
        receiveAddress: null,
        remark: null,
        riderClientStatus: null,
        shortName: null,
        startingLatitude: null,
        startingLongitude: null,
        terminalLatitude: null,
        terminalLongitude: null,
        merchantClientStatus: null,
        orderSn: null,
        result: null,
        dayNum: null,
        startTime: null,
        BtnSaveTitle: null,
        riderToMerchantDistance: null,
        riderToUserDistance: null,
        createTime: null,
        goodsVOS: null,
        goodsLength: null,
        goodsNuall: null,
        merchantMobile: null,
        userMobile: null,
        phone: null,
        titleName: null,
        merchantName: null,
        GoodsTypeShow: true,
        sfBuy: 0,
		status:null,
		riderPhone:""
    })
    const defaultShow = ref(false)
    //地图路线
    const routeLine = reactive<routeLine>({
        points: [],
    })
    //取货点京
    /*startingLongitude	起点经度(商家)
     startingLongitude	起点经度(商家)
     terminalLongitude	终点经度(用户)
     terminalLatitude	终点纬度(用户)
    */

    // 初始化点坐标
    const loactionData = reactive<loactionData>({
        lat: 0,
        lng: 0
    })
    uni.startLocationUpdate({
        success: ((res: any) => {
            // 成功开启定位后进行实时位置更新
            riderLoactionChange()
        }),
        fail: ((err: any) => {
            proxy.$API(proxy).Toast("未检测到开启定位权限！", 'error')
            console.log("startLocationUpdate err = ", JSON.stringify(err));
            //定位失败检测是否开启定位权限   或者GPRS 定位
        })
    })
    const riderLoactionChange = () => {
        uni.onLocationChange((res: any) => {
            //重新设置当前位置
            loactionData.lng = res.longitude
            loactionData.lat = res.latitude
        })
    }
    const setTimeShow = ref(true)
    const covers = reactive<covers>({
        startingLatitude: '',
        startingLongitude: '',
        terminalLatitude: '',
        terminalLongitude: '',
    })
    const statusShowType = ref<boolean>(false)
    // 获取订单详情
    const getDelatis = (Type: number, id: number, lng: string | number, lat: string | number) => {
        /**  Type 订单类型 {0,1,2}   0 新任务 1 待取货 2 配送中
         * orderType 订单状态 {0,1}  0 外卖订单  1  跑腿订单
         *
         */
        let data = {
            longitude: lng,
            latitude: lat,
            orderId: id
        }

        if (Type == 0) {
            // 当为外卖新任务 获取订单详情
            $http.takeAwaynNewTask(data, proxy).then((res: any) => {
                orderObj.titleName = changeTitleText(res.data.riderClientStatus)
                if (res.code == 0) {
                    orderObj.goodsLength = res.data.goodsVOS.length
                    for (let i in orderObj) {
                        for (let j in res.data) {
                            if (i == j) {
                                orderObj[i] = res.data[j]
                            }
                        }
                    }
                    res.data.goodsVOS?.forEach((item: any, index: number | string) => {
                        orderObj.goodsNuall += item.goodsNum
                    });

                    try {
                        orderObj.riderToMerchantDistance = GetDistance(<number>data.latitude, <number>data.longitude, res.data.startingLatitude, res.data.startingLongitude)
                        orderObj.riderToUserDistance = GetDistance(<number>data.latitude, <number>data.longitude, res.data.terminalLatitude, res.data.terminalLongitude)
                    } catch (e) {
                        console.log(e)
                    }
                    setInterval(() => {
                        changeListDis(false);
                    }, 5000);
                }
            }).catch((err: any) => {
                if (err.code == -1) {
                    defaultShow.value = true
                }
            })
            // 当为外卖待取货
        } else if (Type == 1) {
            $http.takeAwayNext(data, true, proxy).then((res: any) => {
                if (res.code == 0) {
                    orderObj.BtnSaveTitle = changeTitleText(res.data.riderClientStatus)
                    orderObj.goodsLength = res.data.goodsVOS.length
                    res.data.goodsVOS?.forEach((item: any, index: number | string) => {
                        orderObj.goodsNuall += item.goodsNum
                    });
                    for (let i in orderObj) {
                        for (let j in res.data) {
                            if (i == j) {
                                orderObj[i] = res.data[j]
                            }
                        }
                    }

                    try {
                        orderObj.riderToMerchantDistance = GetDistance(<number>data.latitude, <number>data.longitude, res.data.startingLatitude, res.data.startingLongitude)
                    } catch (e) {
                        console.log(e)
                    }
                }

                setInterval(() => {
                    changeListDis(false);
                }, 5000);
                //待取货 暂时取消地图
                // covers.startingLongitude = res.data.startingLongitude
                // covers.startingLatitude = res.data.startingLatitude
                // covers.terminalLongitude = res.data.terminalLongitude
                // covers.terminalLatitude = res.data.terminalLatitude
                // res.data.locationVO.locationResultVOs?.forEach((item : any, index : number) => {
                // 	routeLine.points.push(item)
                // }
                // )
                // setTimeout(() => {
                // 	statusShowType.value = true
                // }, 500)
            }).catch((err: any) => {
                console.log(err)
            })
            // 当为配送中
        } else if (Type == 2) {
            $http.takeAwayDeliveryin(data, true, proxy).then((res: any) => {
                if (res.code == 0) {
                    orderObj.titleName = changeTitleText(res.data.riderClientStatus)
                    orderObj.goodsLength = res.data.goodsVOS.length
                    res.data.goodsVOS?.forEach((item: any, index: number | string) => {
                        orderObj.goodsNuall += item.goodsNum
                    });
                    for (let i in orderObj) {
                        for (let j in res.data) {
                            if (i == j) {
                                orderObj[i] = res.data[j]
                            }
                        }
                    }
                }
                orderObj.locationVO.locationResultVOs?.forEach(
                    (item: any, index: number) => {
                        routeLine.points.push(item)
                    }
                )
                setTimeout(() => {
                    statusShowType.value = true
                }, 500)
                covers.startingLongitude = res.data.startingLongitude
                covers.startingLatitude = res.data.startingLatitude
                covers.terminalLongitude = res.data.terminalLongitude
                covers.terminalLatitude = res.data.terminalLatitude

                try {
                    orderObj.riderToMerchantDistance = GetDistance(<number>data.latitude, <number>data.longitude, res.data.startingLatitude, res.data.startingLongitude)
                    orderObj.riderToUserDistance = GetDistance(<number>data.latitude, <number>data.longitude, res.data.terminalLatitude, res.data.terminalLongitude)
                } catch (e) {
                    console.log(e)
                }

                setInterval(() => {
                    changeListDis(true);
                }, 10000);
            }).catch((err: any) => {
                console.log(err)
            })
        }
    }


    const butChange = reactive<any>({
        title: '抢单',
        btn_disable: true,
    })
    //抢单
    const makeOrder = (id: number | string) => {
        let data = {
            id,
        }
        if (butChange.btn_disable) {
            $http
                .makeOrder(data, proxy)
                .then((res: any) => {
                    if (res.code == 0) {
                        proxy.$API(proxy).Toast(res.msg, 'success')
                        butChange.title = '已抢单'
                        butChange.btn_disable = false
                    }
                })
                .catch((err: any) => {
                    proxy.$API(proxy).Toast(err.msg, 'error')
                })
        }
    }
    //我已取货 或者确认到店
    const takeGoods = (orderObj: any, listStatus: number | string) => {
        let id = proxy.$page.options.id
        console.log("listStatus",listStatus)
        if (listStatus == 1 || listStatus == 7) {
            $http.takeGoods(id, '', proxy).then((res: any) => {
                if (res.code == 0) {
                    proxy.$API(proxy).Toast(res.msg, 'success')
                    setTimeout(() => {
                        uni.navigateBack({
                            delta: 1
                        });
                    }, 1000);
                }
            })
            .catch((err: any) => {
                return proxy.$API(proxy).Toast(err.msg, 'error')
            })
            //商品确认送达
        } else if (listStatus == 5) {
            let data = {
            	riderLongitude: locationCacheObj.locationCacheObj.lon,
            	riderLatitude: locationCacheObj.locationCacheObj.lat,
            	orderId: proxy.$page.options.id
            }
            //console.log("delivered:",data);
            $http.delivered(data, proxy).then((res: any) => {
                if (res.code == 0) {
                    proxy.$API(proxy).Toast(res.msg, 'success')
                    orderObj.titleName = '已送达'
                    setTimeout(() => {
                        uni.redirectTo({url: '/pages/Home/Home'})
                    }, 1000);
                }
            }).catch((err: any) => {
                return proxy.$API(proxy).Toast(err.msg, 'error')
            })

            //兼容问题
            // uni.getLocation({
            //     type: "gcJ02",
            //     success: res => {
            //         let data = {
            //             riderLongitude: res.longitude,
            //             riderLatitude: res.latitude,
            //             orderId: proxy.$page.options.id
            //         }
            //         console.log(data)
            //         $http.delivered(data, proxy).then((res: any) => {
            //             if (res.code == 0) {
            //                 proxy.$API(proxy).Toast(res.msg, 'success')
            //                 orderObj.titleName = '已送达'
            //                 setTimeout(() => {
            //                     uni.redirectTo({url: '/pages/Home/Home'})
            //                 }, 1000);
            //             }
            //         }).catch((err: any) => {
            //             return proxy.$API(proxy).Toast(err.msg, 'error')
            //         })
            //     }
            // });
        }
    }
    const locationCacheObj = riderLocationCache();
    let num = 0;
    const changeListDis = (ps: boolean) => {
        //缓存定位
        let lat1 = locationCacheObj.locationCacheObj.lat
        let lon1 = locationCacheObj.locationCacheObj.lon
        if (lat1 != 0 && orderObj.id != null) {
            if (orderObj.startingLatitude > 0) {
                orderObj.riderToMerchantDistance = GetDistance(lat1, lon1, orderObj.startingLatitude, orderObj.startingLongitude);
            }
            if (orderObj.terminalLatitude > 0) {
                orderObj.riderToUserDistance = GetDistance(lat1, lon1, orderObj.terminalLatitude, orderObj.terminalLongitude);
            }
        }
    }

	// 转单
	const orderId = ref('')
	const isShow = ref(false)
	const clickConfirm = (remark:string) => {
		if(remark.trim()==''){
			isShowFalse()
			proxy.$API(proxy).Toast('转单原因不能为空', 'error')
			return
		}

		tfOrder(remark)
		isShowFalse()
	}
	// 打开转单弹出框
	const clickIsShow = () =>{
		if(orderObj.riderClientStatus==1 && orderObj.status==1){
			isShow.value = true
		}else{
			// return 	proxy.$API(proxy).Toast('当前订单不可转单', 'error')
		}
	}

	// 关闭退款弹出框
	const isShowFalse = () => {
		isShow.value = false
	}

	const radiolist = ref([{
			name: '订单不顺路',
			disabled: false
		},
		{
			name: '暂时不能配送',
			disabled: false
		},
		{
			name: '距离当前位置较远',
			disabled: false
		},
		{
			name: '其他',
			disabled: false
		},
	])

	const tfOrder = (msg:any) =>{
		let par = {
			orderId:orderId.value,
			msg:msg
		}

		$http.tfOrder(par,proxy).then(res=>{
			proxy.$API(proxy).Toast('转单成功', 'success')
			setTimeout(()=>{
				uni.navigateBack()
			},500)
		})
	}

	// 电话联系弹出层
	const phoneBtnList = ref([])
	const phoneListShow = ref(false)
	const getPhoneList = () =>{
		// 如果订单未完成可以联系收货人取货人
		// 订单成功不能联系  直接隐藏
		let arr = [
			{
				title:'联系商家',
				phone:orderObj.mobile,
				type:"B"
			},
			{
				title:'联系用户',
				phone:orderObj.phone,
				type:"C"
			},
            {
                title:'注册用户',
                phone:orderObj.userMobile,
                type: "C0"
            },
		]
		if(orderObj.riderClientStatus==4){
			// return 	proxy.$API(proxy).Toast('订单已完成不能联系用户', 'error')
		}
		uni.setStorageSync('phoneBtnList', JSON.stringify(arr))
		
		phoneBtnList.value = [ ...JSON.parse(uni.getStorageSync('phoneBtnList')) ]
	
		phoneListShow.value = true
	}
	const btnCancel = () =>{
		phoneListShow.value = false
	}




    return {
		isShow,
		clickIsShow,
		orderId,
		radiolist,
		clickConfirm,
		isShowFalse,
		phoneListShow,
		getPhoneList,
		phoneBtnList,
		btnCancel,
        AddConfig,
        takeGoods,
        Type,
        confirmChange,
        timeData,
        onChange,
        getDelatis,
        orderObj,
        makeOrder,
        callPhone,
        routeLine,
        butChange,
        defaultShow,
        covers,
        statusShowType,
        setTimeShow

    }
}
